import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'

// createRouter 创建路由实例
// 配置 history 模式
//   1. createWebHistory  : history模式 地址栏不带#
//   2. createHashHistory : hash模式    地址栏带#
// vite 中的环境变量 import.meta.env.BASE_URL 就是 vite.config.js 文件中的配置项
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/LoginPage.vue') //登录页
    },
    {
      path: '/subjects',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/subjects/list', //重定向
      children: [
        {
          path: '/subjects/list', //嵌套路由
          component: () => import('@/views/subjects/SubjectsList.vue'),
          redirect: '/subjects/list/ae',
          children: [
            {
              path: '/subjects/list/ae',
              component: () => import('@/views/subjects/ae.vue')
            },
            {
              path: '/subjects/list/sae',
              component: () => import('@/views/subjects/sae.vue')
            },
            {
              path: '/subjects/list/experimental',
              component: () => import('@/views/subjects/experimental.vue')
            },
            {
              path: '/subjects/list/completion',
              component: () => import('@/views/subjects/completion.vue')
            },
            {
              path: '/subjects/list/adverse',
              component: () => import('@/views/subjects/adverse.vue')
            },
            {
              path: '/subjects/list/recrudescence',
              component: () => import('@/views/subjects/recrudescence.vue')
            }
          ]
        },
        {
          path: '/user/profile', //嵌套路由
          component: () => import('@/views/user/UserProfile.vue')
        },
        {
          path: '/user/acatar', //嵌套路由
          component: () => import('@/views/user/UserAcatar.vue')
        },
        {
          path: '/user/password', //嵌套路由
          component: () => import('@/views/user/UserPassword.vue')
        },
        {
          path: '/appendix/ae', //嵌套路由
          component: () => import('@/views/appendix/AE.vue')
        },
        {
          path: '/appendix/sae', //嵌套路由
          component: () => import('@/views/appendix/SAE.vue')
        },
        {
          path: '/appendix/lifeQuality', //嵌套路由
          component: () => import('@/views/appendix/LifeQuality.vue')
        }
      ]
    }
  ]
})

// 登录访问拦截 => 默认是直接放行
// 根据返回值决定，是放行还是拦截
// 1. undefined / true 直接放行
// 2. false 拦回from的地址页面
// 3. 具体路径 或 路径对象 拦截到对象的地址
//    '/login'  { name: 'login' }
router.beforeEach((to) => {
  // 如果没有token, 且访问的是非登录页，拦截到登录，其他情况正常放行
  const useStore = useUserStore()
  console.log(useStore.token)
  if (!useStore.token && to.path !== '/login') return '/login'
})

export default router
